import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/core/controllers/device_controller.dart';
import 'package:oramemo/widget/gradient_app_head.dart';
import 'package:oramemo/widget/gradient_background.dart';
import 'package:oramemo/common/langs/text_key.dart';

class DeviceListPage extends StatefulWidget {
  const DeviceListPage({super.key});

  @override
  State<DeviceListPage> createState() => _DeviceListPageState();
}

class _DeviceListPageState extends State<DeviceListPage> {
  final DeviceController controller = Get.find();

  @override
  void initState() {
    super.initState();
    _fetchDevices();
  }

  Future<void> _fetchDevices() async {
    await controller.fetchDevices();
    setState(() {});
  }

  Future<void> _unbindDevice(String id) async {
    try {
      await controller.unbindDevice(id);
      _fetchDevices();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(TextKey.deviceUnbindSuccess.tr)),
      );
    } catch (e) {
      _showErrorSnackbar('${TextKey.deviceUnbindFailed.tr}$e');
    }
  }

  void _showErrorSnackbar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    final _isLoading = controller.isLoading;
    final _devices = controller.devices;

    return Column(
      children: [
        GradientAppHead(
          title: TextKey.deviceListTitle.tr,
          actions: IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
            },
          ),
        ),
        Expanded(
          child: GradientBackground(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _devices.isEmpty
                    ? Center(child: Text(TextKey.deviceNoDevices.tr))
                    : ListView.builder(
                        padding: EdgeInsets.zero,
                        itemCount: _devices.length,
                        itemBuilder: (context, index) {
                          final device = _devices[index];
                          return InkWell(
                            onTap: () {
                              Get.back();
                            },
                            child: Container(
                              margin: const EdgeInsets.symmetric(
                                  vertical: 8, horizontal: 16),
                              padding: const EdgeInsets.fromLTRB(10, 4, 0, 5),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: ListTile(
                                title: Text(device.deviceName ?? TextKey.unnamedDevice.tr),
                                subtitle: Text('${TextKey.deviceIdLabel.tr}${device.device?.deviceSn}'),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.input,
                                          color: Colours.gradient_blue),
                                      onPressed: () async {},
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.delete,
                                          color: Colors.red),
                                      onPressed: () async {
                                        final confirm = await Get.dialog<bool>(
                                          AlertDialog(
                                            title: Text(TextKey.deviceDeleteConfirm.tr),
                                            content: Text(TextKey.deviceDeleteMessage.tr),
                                            actions: [
                                              TextButton(
                                                onPressed: () =>
                                                    Get.back(result: false),
                                                child:  Text(TextKey.cancel.tr),
                                              ),
                                              TextButton(
                                                onPressed: () =>
                                                    Get.back(result: true),
                                                child:  Text(TextKey.confirm.tr),
                                              ),
                                            ],
                                          ),
                                        );
                                        if (confirm == true) {
                                          _unbindDevice(
                                              device.id?.toString() ?? '');
                                        }
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
          ),
        ),
      ],
    );
  }
}
